package models

import (
	"fmt"
	"im/utils"
	"time"

	"gorm.io/gorm"
)

type UserBasic struct {
	gorm.Model
	Name          string `gorm:"column:name;type:varchar(100);default:null"`
	PassWord      string `gorm:"column:pass_word;type:varchar(100);default:null"`
	Salt          string
	Phone         string    `valid:"matches(^1[3-9]{1}\\d{9}$)"gorm:"column:phone;type:varchar(20);uniqueIndex;default:null"`
	Email         string    `valid:"email";gorm:"column:email;type:varchar(100);uniqueIndex;default:null"`
	Identity      string    `gorm:"column:identity;type:varchar(50);default:null"`
	ClientIp      string    `gorm:"column:client_ip;type:varchar(50);default:null"`
	ClientPort    string    `gorm:"column:client_port;type:varchar(50);default:null"`
	LoginTime     time.Time `gorm:"column:login_time;type:datetime(3);default:CURRENT_TIMESTAMP(3)"`
	HeartbeatTime time.Time `gorm:"column:heartbeat_time;type:datetime(3);default:null"`
	LogoutTime    time.Time `gorm:"column:logout_time;type:datetime(3);default:null"`
	IsLogon       bool      `gorm:"column:is_logon;default:false"`
	DeviceInfo    string    `gorm:"column:device_info;type:text;default:null"`
}

func (table *UserBasic) TableName() string {
	return "user_basic"
}

func GetUserList() []*UserBasic {
	data := make([]*UserBasic, 10)
	utils.DB.Find(&data)
	for _, v := range data {
		fmt.Println(v)
	}
	return data
}

func FindUserByNameAndPwd(name string, passwd string) UserBasic {
	user := UserBasic{}
	utils.DB.Where("name =? and pass_word=?", name, passwd).First(&user)
	//加密token
	str := fmt.Sprintf("%d", time.Now().Unix())
	tmp := utils.Md5Encode(str)
	utils.DB.Model(&user).Where("id = ?", user.ID).Update("identity", tmp)
	return user
}

func FindUserByName(name string) UserBasic {
	user := UserBasic{}
	utils.DB.Where("name =?", name).First(&user)
	return user
}

func FindUserByPhone(phone string) UserBasic {
	user := UserBasic{}
	utils.DB.Where("phone =?", phone).First(&user)
	return user
}

func FindUserByEmail(email string) UserBasic {
	user := UserBasic{}
	utils.DB.Where("email =?", email).First(&user)
	return user
}

func CreateUser(user UserBasic) *gorm.DB {
	return utils.DB.Create(&user)
}

func DeleteUser(user UserBasic) *gorm.DB {
	return utils.DB.Unscoped().Delete(&user)
}

func UpdateUser(user UserBasic) *gorm.DB {
	return utils.DB.Model(&user).Updates(UserBasic{Name: user.Name, PassWord: user.PassWord, Phone: user.Phone, Email: user.Email})
}
